package com.apps.diet.endpoint;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.apps.diet.domain.Meals;
import com.apps.diet.oxm.GetMealsRequest;
import com.apps.diet.oxm.GetMealsResponse;
import com.apps.diet.service.MealsService;

/**
 * Handles get requests. 
 * <p>
 *<pre>
 * @Endpoint: similar to Spring MVC's @Controller. 
 * @PayloadRoot: similar to Spring MVC's @RequestMapping</pre>
 */
@Endpoint
public class GetMealsEndpoint {

	protected static Logger logger = Logger.getLogger(GetMealsEndpoint.class);

	@Resource(name="mealsService")
	private MealsService mealsService;

	public static final String NAMESPACE_URI = "http://diet.apps.com/ws/schema/diet";

	public static final String REQUEST_LOCAL_NAME = "getMealsRequest";

	@PayloadRoot(localPart = REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI)
	@ResponsePayload
	public GetMealsResponse getMealsResults( @RequestPayload GetMealsRequest getMealsRequest) {
		List<Meals> mealsList = new ArrayList<Meals>();
		GetMealsResponse response = null;
		try {
			String searchText = getMealsRequest.getMealName();
			
			if (searchText == null){
				searchText = "NA";
			}
			
			/*If no searchtext provided, return all result*/
			if (searchText.equals("NA")){
				mealsList = mealsService.getMeals("");
			}else{
				mealsList = mealsService.getMeals(searchText);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			response = new GetMealsResponse();
			response.setCode("FAILURE");
			response.setTotalRecord(0);
			return response;
		}

		response = new GetMealsResponse();
		response.setMeals(mealsList);
		response.setCode("SUCCESS");
		response.setTotalRecord(mealsList.size());

		return response;
	}
}
